﻿
using System;

namespace n_VexProtocol
{
//协议解析器
public static class VexProtocol
{
	public delegate void D_ReceiveType( byte RE_Type );
	public static D_ReceiveType ReceiveType;
	
	public static byte RE_Type;
	
	const byte VM_HEAD = 0xAA;
	
	public const byte VM_NULL = 0x00;	//无效类型
	
	public const byte VM_SETADDR = 0xF0;	//设置地址
	public const byte VM_STORE = 0xF1;		//保存数据
	public const byte VM_READ = 0xF2;		//读取数据
	public const byte VM_CHECK = 0xF3;		//校验和
	
	public const byte VM_ERROR = 0xFE;		//错误信息
	public const byte VM_VERSION = 0xFF;	//版本查询
	
	//---------------------------------------------------
	
	static int Pro_Cnum;
	//static int Pro_VM_status;
	static int Pro_Length;
	
	public static byte[] RE_Data;
	
	public static string Result;
	
	//==============================================================================
	//初始化
	public static void Init()
	{
		RE_Type = VM_NULL;
		Pro_Cnum = 0;
		Pro_Length = 0;
		//Pro_VM_status = 0;
		
		RE_Data = new byte[500];
	}
	
	//添加一个数据
	public static void Deal( byte d )
	{
		Result += d.ToString( "X" ).PadLeft( 2, '0' ) + " ";
		
		RE_Data[Pro_Cnum] = d;
		
		Pro_Cnum++;
		//判断是否为合法数据头部
		if( Pro_Cnum == 1 ) {
			if( d != VM_HEAD ) {
				//... 报错
				Pro_Cnum = 0;
			}
			return;
		}
		//判断是否为数据长度低位
		if( Pro_Cnum == 2 ) {
			Pro_Length = d;
			return;
		}
		//判断是否为数据长度高位
		if( Pro_Cnum == 3 ) {
			Pro_Length += d * 256;
		}
		if( Pro_Cnum - 3 == Pro_Length ) {
			Pro_Cnum = 0;
			
			RE_Type = RE_Data[3];
			
			if( ReceiveType != null ) {
				ReceiveType( RE_Type );
			}
		}
	}
	
	//清空返回类型标志
	public static void ClearReType()
	{
		RE_Type = VM_NULL;
		
		//防止协议下载到一半出现问题, 能够复位 2020.11.19
		Pro_Cnum = 0;
	}
}
}




